#include "Cfg.h"
#include "stdlib.h"

CCfg::CCfg(wstring fileName)
{
    m_sFileName = fileName;
    Load();
}

CCfg::~CCfg(void)
{
}


int CCfg::Load()
{
    wifstream fileStream(m_sFileName.c_str());
    if (fileStream.fail())
    {
        return 1;
    }
    Property *property = NULL;
    wstring lineBuff;
    while (getline(fileStream, lineBuff))
    {
        property = new Property();
        if (!ParseLine(lineBuff, *property))
        {
            m_vProperties.push_back(*property);
        }
    }

    fileStream.close();
    return 0;
}

//0:success; 1:comment; -1:wrong format
int CCfg::ParseLine(wstring lineBuff, Property &property)
{
    //if comments
    if (Trim(lineBuff).find_first_of(L"#") == 0)
    {
        return 1;
    }

    wstring::size_type splitIndex = lineBuff.find_first_of(L"=");
    if (splitIndex != wstring::npos)
    {
        property.name = Trim(lineBuff.substr(0, lineBuff.find_first_of(L"=")));
        property.value = Trim(lineBuff.substr(lineBuff.find_first_of(L"=") + 1));
        return 0;
    }
    else
    {
        return -1;
    }
}

wstring CCfg::Trim(wstring sourceStr)
{
    wstring newStr = sourceStr;
    newStr.erase(newStr.find_last_not_of (L" ") + 1);
    newStr.erase(0, newStr.find_first_not_of (L" "));
    return newStr;
}


wstring CCfg::GetProperty(wstring propName)
{
    for(vector<Property>::size_type i = 0; i < m_vProperties.size(); i ++)
    {
        if (!propName.compare(m_vProperties[i].name))
        {
            return m_vProperties[i].value;
        }
    }

    return L"";
}

int CCfg::SetProperty(wstring propName, wstring propValue)
{
    for(vector<Property>::size_type i = 0; i < m_vProperties.size(); i ++)
    {
        if (!propName.compare(m_vProperties[i].name))
        {
            m_vProperties[i].value = propValue;
            return 0;
        }
    }

    Property property;
    property.name = propName;
    property.value = propValue;
    m_vProperties.push_back(property);
    return 0;
}

int CCfg::Save()
{
    wofstream fileStream(m_sFileName.c_str());
    if (fileStream.fail())
    {
        return 1;
    }

    for(vector<Property>::size_type i = 0; i < m_vProperties.size(); i ++)
    {
        fileStream << m_vProperties[i].name << L" " << m_vProperties[i].value << endl;
    }

    fileStream.close();
    return 0;
}
